package boids
{
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.KeyboardEvent;
	import flash.utils.getTimer;
	
	import mx.collections.ArrayCollection;

	public class BoidsMain extends Sprite
	{
		private static var MAX_UNITS:uint	= 25;
		private static var SPAWN_AREA:uint	= 100;
		private var units:ArrayCollection = new ArrayCollection();
		
		private var leftKeyDown:Boolean = false;
		private var rightKeyDown:Boolean = false;
		
		public function BoidsMain()
		{
		
		}
		
		public function init():void
		{
			for (var i:uint=0; i<MAX_UNITS; i++){
				var boid:BoidUnit
				
				if(i>MAX_UNITS/2){
					boid = new BoidUnit(true);
				}else{
					boid = new BoidUnit(false);
				}
				
				boid.x = Math.random()*(this.parent.width/2+SPAWN_AREA)-(this.parent.width/2-SPAWN_AREA) ;
				boid.y = Math.random()*(this.parent.height/2+SPAWN_AREA)-(this.parent.width/2-SPAWN_AREA) ;
	
				units.addItem(boid);
				this.addChild(boid);
			}
			
			
			this.addEventListener(Event.ENTER_FRAME, onEnterFrame);	
			this.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
			this.addEventListener(KeyboardEvent.KEY_UP, onKeyUp);
		}
		
		private function onEnterFrame(e:Event):void
		{
			var leaderUnit:BoidUnit = units.getItemAt(0) as BoidUnit;
			leaderUnit.setThrusters(false, false, 1);
			
			if(rightKeyDown)
				leaderUnit.setThrusters(true, false, 0.5);				
			if(leftKeyDown)
				leaderUnit.setThrusters(false, true, 0.5);
			
			for each(var boidUnit:BoidUnit in units){
				// check if this correct?
				boidUnit.updateBodyEuler(getTimer());
			
				if(boidUnit.x >stage.width)
					boidUnit.x = 0;
				if(boidUnit.x < 0)
					boidUnit.x = stage.width;
				if(boidUnit.y >stage.height)
					boidUnit.y = 0;	
				if(boidUnit.y < 0)
					boidUnit.y = stage.height;	
			}	
		}		
		
		private function doBoidUnitAI(unit:BoidUnit):void {
			
		}
		
		private function onKeyDown(e:KeyboardEvent):void{
			trace(e.keyCode);
			switch(e.keyCode){
				case 37:
					leftKeyDown = true;
					break;
				case 39:
					rightKeyDown = true;
					break;		
			}					
		}
		
		private function onKeyUp(e:KeyboardEvent):void{
			
			switch(e.keyCode){
				case 37:
					leftKeyDown = false;
					break;
				case 39:
					rightKeyDown = false;
					break;		
			}					
		}		
	}
}